package com.kiki.task;

import cn.hutool.core.date.DateTime;
import com.kiki.common.core.domain.entity.SysUser;
import com.kiki.recommendations.domain.Recommendations;
import com.kiki.recommendations.mapper.RecommendationsMapper;
import com.kiki.song.domain.main.Song;
import com.kiki.song.service.impl.SongServiceImpl;
import com.kiki.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 *  离线推荐分时期的接口调用
 *
 */
//'0 2 * * *'表示每天都执行一次，每次都在凌晨2点多
@Component("OffLineRecommendationTask")
public class OffLineLineRecommendationTask1 {
    @Autowired
    private SongServiceImpl songServiceImpl;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RecommendationsMapper recommendationsMapper;
    public void getSongList(){
        //获取所有用户的信息，除了管理员
        List<SysUser> sysUsers = sysUserMapper.selectUserList(new SysUser());
        List<Long> userIdList = new ArrayList<>();
        //使用流获取所有用户的userId，剔除掉userId为1的用户
        sysUsers.stream().filter(sysUser -> !sysUser.isAdmin()).forEach(sysUser -> {
            userIdList.add(sysUser.getUserId());
        });
        Map<String,List<Song>> userSongList = new HashMap<>();
        //使用流获取每个用户的离线推荐歌曲列表
        userIdList.stream().forEach(userId -> {
            List<Song> songs = songServiceImpl.OffLineRecommendModel(userId.intValue());
            userSongList.put(userId.toString(),songs);
        });
        //清除掉旧的推荐歌曲
        recommendationsMapper.cleanOldData();
        //打印出来这些用户的推荐歌曲，并且打印用户的id,但是音乐信息只需要打印歌名和歌手即可
        userSongList.forEach((userId,songs) -> {
            songs.forEach(song -> {
                //加入到推荐表中
                Recommendations recommendations = new Recommendations();
                recommendations.setUserId(Long.parseLong(userId));
                recommendations.setSongId(song.getSongId());
                recommendations.setType("OffLine");
                recommendations.setRecommendTime(new Date());
                recommendationsMapper.insertRecommendations(recommendations);
            });
        }
        );
    }
}
